package com.securitydemo.config.security.provider;

import com.securitydemo.securitylogin.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class HYAbstractUserDetailsAuthenticationProvider implements AuthenticationProvider {


    @Autowired
    UserDetailServiceImpl userDetailService;

    /**
     * 填写校验逻辑并封装用户的返回数据
     *
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // 获取用户token
        Object credentials = authentication.getCredentials();
        String token = credentials.toString();
        // 验证用户登录信息
        UserDetails userDetails = userDetailService.loadUserByUsername(token);
        // 获取用户详情
        HYAbstractAuthenticationToken hyAbstractAuthenticationToken = new HYAbstractAuthenticationToken(userDetails, null, userDetails
                .getAuthorities());
        return hyAbstractAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (HYAbstractAuthenticationToken.class
                .isAssignableFrom(authentication));
    }
}
